package com.csxy.lsh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.lsh.R;
import com.csxy.lsh.api.UcenterClient;
import com.csxy.lsh.entity.StatisticsDaily;
import com.csxy.lsh.mapper.StatisticsMapper;
import com.csxy.lsh.service.StatisticsService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsServiceImpl extends ServiceImpl<StatisticsMapper,StatisticsDaily> implements StatisticsService {
    @Autowired
    private UcenterClient ucenterClient;
    @Override
    public void createStatisticsByDay(String day) {

        QueryWrapper<StatisticsDaily> Wrapper = new QueryWrapper<>();
        Wrapper.eq("date_calculated",day);
        baseMapper.delete(Wrapper);

        R registerR = ucenterClient.countRegister(day);
        Integer countRegister = (Integer) registerR.getData().get("countRegister");

        StatisticsDaily daily = new StatisticsDaily();
        daily.setRegisterNum(countRegister);
        daily.setRegisterNum(countRegister);
        daily.setCourseNum(RandomUtils.nextInt(100,200));
        daily.setLoginNum(RandomUtils.nextInt(200,300));
        daily.setVideoViewNum(RandomUtils.nextInt(300,400));
        daily.setDateCalculated(day);

        baseMapper.insert(daily);

    }

    @Override
    public Map<String, Object> showData(String type, String begin, String end) {
        System.out.println("showData参数: type=" + type + ", begin=" + begin + ", end=" + end);
        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.select("date_calculated",type);
        wrapper.between("date_calculated",begin,end);

        List<StatisticsDaily> dailyList =baseMapper.selectList(wrapper);
        System.out.println("查出的dailyList: " + dailyList);


        List<String> xlist=new ArrayList<>();
        List<Integer> ylist=new ArrayList<>();

        for (StatisticsDaily daily:dailyList){
            xlist.add(daily.getDateCalculated());

            if ("register_num".equals(type)){
                ylist.add(daily.getRegisterNum());
            }
            if ("login_num".equals(type)){
                ylist.add(daily.getLoginNum());
            }
            if ("video_view_num".equals(type)){
                ylist.add(daily.getVideoViewNum());
        }
            if ("course_num".equals(type)){
                ylist.add(daily.getCourseNum());
            }
            }
        HashMap<String,Object> map = new HashMap<>();
        map.put("xlist",xlist);
        map.put("ylist",ylist);
        System.out.println("返回map: " + map);
        return map;

    }


}
